#include "SeqList.h"


////////////////////////////////////////////////////////////////
//void SqlistInit(SL* arr) {
//	memset(arr->a, 0, sizeof(SQDataType) * N);
//	arr->size = 0;
//}
//
//void SqlistPushBack(SL* arr, SQDataType x) {
//	if (arr->size >= N) {
//		printf("The Seqlist is FULL\n");
//		return;
//	}
//	(arr->a)[arr->size] = x;
//	(arr->size)++;
//}
//void SqlistPushFront(SL* arr, SQDataType x);
//void SqlistPopBack(SL* arr);
//void SqlistPopFront(SL* arr);
////////////////////////////////////////////////////////////////


void SqlistDestory(SL* arr) {
	free(arr->a);
	arr->a = NULL;
	arr->capacity = 0;
}

void SqlistCheckCapacity(SL* arr) {
	if (arr->size == arr->capacity) {
		int newcapacity = (arr->capacity == 0 ? 4 : arr->capacity * 2);
		SQDataType* tmp = (SQDataType*)realloc(arr->a, newcapacity * 2 * sizeof(SQDataType));
		if (tmp == NULL) {
			printf("realloc fail\n");
			exit(-1);
		}
		else {
			arr->a = tmp;
			arr->capacity = newcapacity;
		}
	}
}

void SqlistInit(SL* arr) {
	arr->a = NULL;
	arr->size = 0;
	arr->capacity = 0;
}

void SqlistPushBack(SL* arr, SQDataType x) {
	SqlistCheckCapacity(arr);

	(arr->a)[arr->size] = x;
	++(arr->size);
}

void SqlistPushFront(SL* arr, SQDataType x) {
	SqlistCheckCapacity(arr);

	int end = (arr->size) - 1;
	while (end >= 0) {
		(arr->a)[end + 1] = (arr->a)[end];
		--end;
	}
	(arr->a)[0] = x;
	++(arr->size);
}

void SqlistPopBack(SL* arr) {
	assert(arr->size > 0);

	// (arr->a)[arr->size - 1] = 0;
	--(arr->size);
}

void SqlistPopFront(SL* arr) {
	assert(arr->size > 0);
	for (int start = 1; start < (arr->size); start++)
		(arr->a)[start - 1] = (arr->a)[start];
	--(arr->size);
}

void SqlistInsert(SL* arr, int pos, SQDataType x) {
	assert(pos < arr->size);
	SqlistCheckCapacity(&arr);

	int end = (arr->size) - 1;
	while (end >= pos) {
		(arr->a)[end + 1] = (arr->a)[end];
		--end;
	}
	(arr->a)[pos] = x;
	++(arr->size);
}

void SqlistErase(SL* arr, int pos) {
	assert(pos < (arr->size));
	int start = pos + 1;
	for ( ; start < (arr->size); start++)
		(arr->a)[start - 1] = (arr->a)[start];
	--(arr->size);
}

void SqlistFind(SL* arr, SQDataType x) {
	for (int i = 0; i < (arr->size); ++i) {
		if ((arr->a)[i] == x)
			return i;
	}
	return -1;
}

void SqlistModity(SL* arr, int pos, SQDataType x) {
	assert(pos < (arr->size));
	(arr->a)[pos] = x;
}

void SqlistPrint(SL* arr) {
	for (int i = 0; i < arr->size; ++i) {
		printf("%d ", (arr->a)[i]);
	}
	printf("\n");
}
